/**
 * 		MD5Encryptor.java
 *  Adrián E. Córdoba 		14/07/2013
 */
package ar.com.adriancordoba.app.common.encryptor;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;

import ar.com.adriancordoba.app.common.log.Log;

/**
 * 
 * @author Adrián E. Córdoba
 * 
 */
public class MD5Encryptor implements Encryptor{
	private MessageDigest messageDigest;
	private final static Logger logger = Log.getLogger();

	/**
	 * 
	 */
	public MD5Encryptor() {
		try {
			messageDigest = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			logger.log(Level.SEVERE,
					"Cannot get MessageDiget in order to encrypt text.");
			logger.log(Level.SEVERE, e.getMessage());
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @param text
	 * @return
	 */
	public String encrypt(String text) {
		String encryptedText = null;
		if ((messageDigest != null) && (text != null)) {
			byte[] textArray = text.getBytes();
			textArray = messageDigest.digest(textArray);
			encryptedText = byteArrayToHexString(textArray);
		}
		return encryptedText;
	}

	/**
	 * 
	 * @param b
	 * @return
	 */
	private String byteArrayToHexString(byte[] b) {
		StringBuffer sb = new StringBuffer(b.length * 2);
		for (int i = 0; i < b.length; i++) {
			int v = b[i] & 0xff;
			if (v < 16) {
				sb.append('0');
			}
			sb.append(Integer.toHexString(v));
		}
		return sb.toString().toUpperCase();
	}

	/**
	 * @return the digest
	 */
	public MessageDigest getDigest() {
		return messageDigest;
	}

	/**
	 * @param digest the digest to set
	 */
	public void setDigest(MessageDigest messageDigest) {
		this.messageDigest = messageDigest;
	}

}
